Program to Swap two Numbers with using third variable and without using third variable in c++

Swapping of Numbers with  in C++

            Swapping of two variables is normally done using third variable but we can do the same without using third variable. In this you will learn how the swapping of two variables is done 

  1.  Using third variable
  2.  Without using third variable
  3.  Using a function 

            All the solutions are divided into two sections 
  • Section 1 Logic
  • Section 2 Code 


 

Swapping of two Numbers Using Third Variable

This is the easiest and most common method to swap two numbers.

Logic

  • Input two numbers.
  • Declare third (temporary) variable.
  • Assign value of first variable to temp.
  • Assign value of second to first.
  • Assign value of temp to second.
  • Print the numbers.

Code 

#include <iostream>
using namespace std;

int main() {
    cout<<"Enter two numbers "<<endl;
    
    int a,b;
    cin>>a>>b;
    
    int temp;
    
    temp = a;
    a = b;
    b = temp;
    
    cout<<"The numbers after swapping are ";
cout<<a<<" "<<b<<endl;
    
    return 0;
}

***

Swapping of two Numbers Without Using Third Variable

This another simple and easy to understand method. It includes arithmatic operations such has addition and subtraction for swapping the numbers.

Logic

  • Input two numbers.
  • Add the numbers and store the sum in a.
  • Subtract b from a and store result in b.
  • Subtract b from a and store result in a.
  • Print the numbers.

Code 

#include <iostream>
using namespace std;

int main() {
    cout<<"Enter two numbers "<<endl;
    
    int a,b;
    cin>>a>>b;
    
    a = a + b;
    b = a - b;
    a = a - b;

    cout<<"The numbers after swapping are ";
    cout<<a<<" "<<b<<endl;
    
    return 0;
}
    

***

Swapping of two Numbers Using Function 

In this method we use a predefined c++ function swap. 

Logic

  • Take two Numbers.
  • Use the C++ function swap.
  • Print the Numbers.

Code 

#include <bits/stdc++.h> 
using namespace std;


int main() {
    cout<<"Enter two numbers "<<endl;
    
    int a,b;
    cin>>a>>b;
    
    swap(a,b);
 
    cout<<"The numbers after swapping are ";
    cout<<a<<" "<<b<<endl;
    
    return 0;
}
 
***


Our Hackerrank Code Solutions
  1.  Time Conversion
  2.  Migratory Birds

!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments